﻿using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using miniMana.Entity.EntityBase;

namespace miniMana.Repository.BaseRepository
{
    /// <summary>
    /// 通用仓储类
    /// </summary>
    public class Repository<T, TId, TDbContext> : IRepository<T, TId>
        where T : class, IBaseEntity<TId>
        where TDbContext : DbContext
    {

        /// <summary>
        /// 实体集合
        /// </summary>
        private DbSet<T> DbSet { get; }
        /// <summary>
        /// DB上下文
        /// </summary>
        protected readonly TDbContext context;
        public Repository(TDbContext context)
        {
            this.context = context;
            DbSet=context.Set<T>();
        }


        /// <summary>
        /// 事务
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public IDbContextTransaction BeginTransaction()
        {
            return context.Database.BeginTransaction();
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public IQueryable<T> Query()
        {
            return DbSet;
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="entity"></param>
        public void Add(T entity)
        {
            DbSet.Add(entity);
        }

        /// <summary>
        /// 批量新增
        /// </summary>
        /// <param name="entity"></param>
        public void AddRange(IEnumerable<T> entity)
        {
            DbSet.AddRange(entity);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="entity"></param>
        public void Delete(T entity)
        {
            DbSet.Remove(entity);
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="entity"></param>
        public void Update(T entity)
        {
            DbSet.Update(entity);
        }

        /// <summary>
        /// 同步保存
        /// </summary>
        public void Save()
        {
            context.SaveChanges();
        }

        /// <summary>
        /// 异步保存
        /// </summary>
        /// <returns></returns>
        public Task SaveAsync()
        {
            return context.SaveChangesAsync();
        }
    }

    public class Repository<T, TDbContext> : Repository<T, int, TDbContext>, IRepository<T>
        where T : class, IBaseEntity<int>
         where TDbContext : DbContext
    {
        /// <summary>
        /// DB上下文
        /// </summary>
        protected readonly TDbContext context;
        
        public Repository(TDbContext context) : base(context)
        {
        }
    }
}
